﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GUIServerConnectorAPI;
using EntityModel;
using ApplicationConfiguration;

namespace GUIServerConnector
{
    public class Authenticator : MarshalByRefObject, IAuthenticator
    {
        private TeleasistentaEntities entities;
        
        public Authenticator()
        {
            entities = new TeleasistentaEntities(AppConfiguration.getInstance().getProperty("Database", "connectionString"));
        }

        private bool hashEquals(byte[] hash1, byte[] hash2)
        {
            if (hash1 == null)
            {
                if (hash2 == null) return true;
                return false;
            }
            if (hash2 == null) return false;
            if ((hash1.Length < 16) || (hash2.Length < 16)) return false;
            for (int byteIndex = 0; byteIndex < 16; byteIndex++)
                if (hash1[byteIndex] != hash2[byteIndex]) return false;
            return true;
        }

        public LoginData login(string userName, byte[] passwordHash)
        {
            User user = entities.Users.SingleOrDefault(un => un.Username.Equals(userName));
            if ((user != null) && hashEquals(passwordHash, user.Password))
            {
                LoginData loginData = new LoginData(Guid.NewGuid(), (AccountType) Enum.Parse(typeof(AccountType), user.Rol));
                Sesiune session = new Sesiune();
                session.idSesiune = loginData.sessionId;
                session.idUser = user.idUser;
                session.Start_sesiune = DateTime.Now;
                session.Stop_sesiune = null;
                entities.Sesiunes.AddObject(session);
                entities.SaveChanges();
                return loginData;
            }
            throw new AuthenticationException(Strings.InvalidCredentials);
        }

        public void logout(Guid sessionId)
        {
            Sesiune session = entities.Sesiunes.SingleOrDefault(sid => sid.idSesiune == sessionId);
            if ((session != null) && (session.Stop_sesiune == null))
            {
                session.Stop_sesiune = DateTime.Now;
                entities.SaveChanges();
            }
            throw new AuthenticationException(Strings.InvalidSessionID);
        }
    }
}
